
//  DDNetworkSwitchHelper.m
//  hnGovernment
//
//  Created by zhn on 2017/3/18.
//  Copyright © 2017年 安仔. All rights reserved.
//

#import "DDNetworkSwitchHelper.h"
#import "DDcacheManager.h"
@interface DDNetworkSwitchHelper()
@property (nonatomic,strong) UIAlertController *controller;
@property (nonatomic,copy) NSArray <DDServiceModel *>*serviceArray;
@property (nonatomic,strong) DDServiceModel *defaultModel;
@end

@implementation DDNetworkSwitchHelper
+ (instancetype)shateInstance {
    static DDNetworkSwitchHelper *helper;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[DDNetworkSwitchHelper alloc]init];
    });
    return helper;
}

- (void)initServiceArray:(NSArray<DDServiceModel *> *)serviceArray defaultService:(DDServiceModel *)defaultService{
    self.serviceArray = serviceArray;
    self.defaultModel = defaultService;
    if (![self getServiceIP]) {
        [self cacheServiceIP:self.defaultModel.ip];
    }
}


- (void)showSwitchMenu {
    NSString *serviceTitle;
    for (DDServiceModel *item in self.serviceArray) {
        if ([item.ip isEqualToString:[self getServiceIP]]) {
            serviceTitle = item.name;
        }
    }
    NSString *titleString = [NSString stringWithFormat:@"切换服务器 - 当前:%@",serviceTitle];
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:titleString message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (DDServiceModel *item in self.serviceArray) {
        UIAlertActionStyle style;
        if ([item.ip isEqualToString:[self getServiceIP]]) {
            style = UIAlertActionStyleDestructive;
        }else {
            style = UIAlertActionStyleDefault;
        }
        UIAlertAction *action = [UIAlertAction actionWithTitle:item.name style:style handler:^(UIAlertAction * _Nonnull action) {
            [cacheManager clearUserInfo];
            [self cacheServiceIP:item.ip];
            [SVProgressHUD showInfoWithStatus:@"环境切换成功,应用将被杀死,请重新打开。"];
            // 杀死应用
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                exit(0);
            });
        }];
        [controller addAction:action];
    }
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [controller addAction:action];
    self.controller = controller;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:self.controller animated:YES completion:nil];
}

- (void)cacheServiceIP:(NSString *)IP {
    [[NSUserDefaults standardUserDefaults]setObject:IP forKey:@"ServiceIP"];
}

- (NSString *)getServiceIP {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"ServiceIP"];
}


@end
